import $ from 'jquery'
import {Map} from '../tool'
import store from 'store'

export default class Ajaxs {
    static child = new Ajaxs()
    static single() { return Ajaxs.child }
    key = '__roa_key__'
    constructor() {
        console.log(store.get(this.key))
        this.defProps = { ...this.props }
        this.reload()
    }
    reload = () => {
        this.props.user_loginKey = store.get(this.key)
        store.clearAll()
    }
    save = () => {
        store.remove(this.key)     
        store.set(this.key, this.props.loginKey)
    }
    clear = (value) => {
        this.props = { ...this.defProps }
        store.clearAll()
    }
    props = {
        islogin:false,
        loginKey: undefined,
    }
    jsonp = (props) => {
        $.ajax({
            type: "get",
            async: false,
            timeout: 500,
            url: props.url,
            data: props.data,
            dataType: "jsonp",
            jsonp: "callback",
            success: ()=>{
                console.log(props.log+': success')
            },
            error: (XMLHttpRequest, textStatus, errorThrown) => {
                console.log(props.log+': error')
                alert(XMLHttpRequest.status + "  " + XMLHttpRequest.readyState + "      " + textStatus);
            },
            complete: (XMLHttpRequest, status) => {
                if (status === 'timeout') {
                    alert(props.info + ' ' + '请求超时')
                }
            }
        }).then((res) => {
            if (res.msg === 'userDisappear') {
                alert('用户丢失')
                this.props.islogin = false
                this.clear()
            }
            props.comp(res)
        })
    }
    ajaxLogin = (mobilephone, password, loginKey, callback) => {
        this.jsonp({
            log: '登录',
            url: setup.url.memberLogin,
            data: {
                'mobilephone': mobilephone,
                'password': password,
                'loginKey': loginKey,
            },
            comp: (res) => {
                if (callback !== null) callback(res)
            },
        })
    }
    
}